//
//  ClubFollowSettingViewController.swift
//  77Club
//
//  Created by Apple on 2024/12/30.
//

import UIKit

class ClubFollowSettingViewController: ClubBaseViewController {
    
    private let backButton = c_make_ex(UIButton.self)
        .image("Common_blackBack").end()
    private let titleLabel = c_make_ex(UILabel.self)
        .text("关注设置").color(.black).font(16.font_semiBold)
        .alignment(.center).end()
    private let topView = c_make_ex(UIView.self)
        .bgColor(.white).corner(12.0.Scale).end()
    private let topTitleLab = c_make_ex(UILabel.self)
        .color("#323233").text("选择显示类别（单选）：")
        .font(14.font_medium).end()
    private let attentionButton = UIIconButton(style: .leading(itemSpace: 4))
    private let virtualButton = UIIconButton(style: .leading(itemSpace: 4))
    private let lineView = c_make_ex(UIView.self)
        .bgColor("#EBEBEB").corner(12.0.Scale).end()
//    private let valueLabel = c_make_ex(UILabel.self)
//        .color("#969799").text("400").corner(8).alignment(.center)
//        .font(16.font_semiBold).bgColor("#EDEEF0").end()
    private let virtualTextF = c_make_ex(UITextField.self)
        .color("#FF7700").corner(8).border("#FF7700", width: 1)
        .font(16.font_semiBold).alignment(.center).end()
    private let bottomView = c_make_ex(UIView.self)
        .bgColor(.white).corner(12.0.Scale).end()
    private let bottomTitleLab = c_make_ex(UILabel.self)
        .color("#323233").text("自定义关注称呼：")
        .font(14.font_medium).end()
    private let nameTextF = c_make_ex(UITextField.self)
        .corner(8).bgColor("#F7F8FA").font(16.font_semiBold)
        .placeholder("请输入称呼（例：#人关注）").end()
    private let numberImg = c_make_ex(UIButton.self)
        .image("Forum_edit_number").end()
    private let saveButton = c_make_ex(UIButton.self)
        .corner(19.0.Scale).bgImage(UIImage.colorToImage(color: "#FF7700".toColor))
        .bgImage(UIImage.colorToImage(color: "#E1E2E5".toColor),state: .disabled)
        .text("保存").color(.white).font(14.font_semiBold).end()
    
    var communityId = ""
    var updateSquareSetting:((_:ClubSquareSettingModel)->())?
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    var model: ClubSquareSettingModel?{
        didSet{
            guard let md = model else { return }
            
            if md.bgImg == "1" {
                attentionButton.isSelected = true
                virtualButton.isSelected = false
            }else{
                attentionButton.isSelected = false
                virtualButton.isSelected = true
                var numStr = md.logo
                if numStr == "0"{
                    numStr = ""
                }
                virtualTextF.text = numStr
            }
            var nameStr = md.content
            if nameStr == "未设置" {
                nameStr = ""
            }
            nameTextF.attributedText = createAttributedText(from: nameStr)
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        view.subviews{
            backButton
            titleLabel
            topView.subviews{
                topTitleLab
                attentionButton
                virtualButton
                lineView
//                valueLabel
                virtualTextF
            }
            bottomView.subviews{
                bottomTitleLab
                nameTextF
                numberImg
            }
            saveButton
        }
        
        backButton.leading(0).top(.statusHeight).width(56).height(44)
        titleLabel.centerHorizontally()
        titleLabel.CenterY == backButton.CenterY
        topView.leading(16.0.Scale).trailing(16.0.Scale).top(.navi_height + 12.0.Scale).height(142.0.Scale)
        bottomView.leading(16.0.Scale).trailing(16.0.Scale).height(135.0.Scale)
        bottomView.Top == topView.Bottom + 24.0.Scale
        saveButton.bottom(.safe_bottom + 9).leading(16.0.Scale).trailing(16.0.Scale).height(38.0.Scale)
        topTitleLab.leading(12.0.Scale).top(12.0.Scale)
        attentionButton.leading(12.0.Scale).top(48.0.Scale).height(20.0.Scale)
        lineView.leading(12.0.Scale).trailing(12.0.Scale).height(1).top(86.0.Scale)
        virtualButton.leading(12.0.Scale).height(20.0.Scale)
        virtualButton.Top == lineView.Bottom + 18.0.Scale
        bottomTitleLab.leading(12.0.Scale).top(12.0.Scale)
        nameTextF.top(44.0.Scale).leading(12.0.Scale).trailing(12.0.Scale).height(46.0.Scale)
        numberImg.leading(12.0.Scale).width(58.0.Scale).height(25.0.Scale)
        numberImg.Top == nameTextF.Bottom + 8.0.Scale
//        valueLabel.trailing(12.0.Scale).width(140.0.Scale).height(30.0.Scale)
//        valueLabel.CenterY == attentionButton.CenterY
        virtualTextF.trailing(12.0.Scale).width(140.0.Scale).height(32.0.Scale)
        virtualTextF.CenterY == virtualButton.CenterY
        
        attentionButton.style { v in
            v.iconSize = CGSize(width: 20.0.Scale, height: 20.0.Scale)
            v.setImage("Forum_edit_check".toImage, for: .normal)
            v.setImage("Forum_edit_checkSel".toImage, for: .selected)
            v.setTitleColor("#323233".toColor, for: .normal)
            v.setTitle("实际关注人数", for: .normal)
            v.titleLabel?.font = 14.font_medium
            v.contentHorizontalAlignment = .left
            v.addTarget(self, action: #selector(clickRealityButton), for: .touchUpInside)
        }
        virtualButton.style { v in
            v.iconSize = CGSize(width: 20.0.Scale, height: 20.0.Scale)
            v.setImage("Forum_edit_check".toImage, for: .normal)
            v.setImage("Forum_edit_checkSel".toImage, for: .selected)
            v.setTitleColor("#323233".toColor, for: .normal)
            v.setTitle("虚拟人数", for: .normal)
            v.titleLabel?.font = 14.font_medium
            v.contentHorizontalAlignment = .left
            v.addTarget(self, action: #selector(clickVirtualButton), for: .touchUpInside)
        }
        nameTextF.style { v in
            v.placehold("#969799".toColor, font: 16.font_semiBold)
            let leftV = UIView(frame: CGRect(x: 0, y: 0, width: 12.0.Scale, height: 12.0.Scale))
            v.leftView = leftV
            v.leftViewMode = .always
            // 添加监听实时变化
            v.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
            v.delegate = self
        }
        virtualTextF.style { v in
            let rightV = UIView(frame: CGRect(x: 0, y: 0, width: 30.0.Scale, height: 32.0.Scale))
            let editImg = UIImageView(frame: CGRect(x: 4.0.Scale, y: 8.0.Scale, width: 16.0.Scale, height: 16.0.Scale))
            editImg.image = "Forum_edit_edit".toImage
            rightV.addSubview(editImg)
            let leftV = UIView(frame: CGRect(x: 0, y: 0, width: 8.0.Scale, height: 32.0.Scale))
            v.leftView = leftV
            v.leftViewMode = .always
            v.rightView = rightV
            v.rightViewMode = .always
            v.contentHorizontalAlignment = .center
        }

        backButton.addTarget(self, action: #selector(clickBackButton), for: .touchUpInside)
        saveButton.addTarget(self, action: #selector(clickSaveButton), for: .touchUpInside)
        numberImg.addTarget(self, action: #selector(clickNumberButton), for: .touchUpInside)
    }

}


extension ClubFollowSettingViewController: UITextFieldDelegate {
    
    @objc private func clickRealityButton(){
        
        if !attentionButton.isSelected {
            attentionButton.isSelected = true
            virtualButton.isSelected = false
        }
    }
    
    @objc private func clickVirtualButton(){
        
        if !virtualButton.isSelected {
            virtualButton.isSelected = true
            attentionButton.isSelected = false
        }
    }
    
    @objc private func clickNumberButton(){
        // 判断是否已经有 #
        if nameTextF.text?.contains("#") ?? false {
            return
        }
                
        // 获取光标的位置
        if let selectedRange = nameTextF.selectedTextRange {
            let cursorPosition = nameTextF.offset(from: nameTextF.beginningOfDocument, to: selectedRange.start)
                    
            // 在光标位置插入 #
            var text = nameTextF.text ?? ""
            text.insert("#", at: text.index(text.startIndex, offsetBy: cursorPosition))
            nameTextF.attributedText = createAttributedText(from: text)
                    
            // 重新设置光标位置
            if let newPosition = nameTextF.position(from: selectedRange.start, offset: 1) {
                nameTextF.selectedTextRange = nameTextF.textRange(from: newPosition, to: newPosition)
            }
        }
    }
    
    @objc private func clickSaveButton(){
        
        let system_type = attentionButton.isSelected ? "1" : "2"
        var guanzhu_num = ""
        if let num = virtualTextF.text, num.count > 0 {
            if virtualButton.isSelected {
                guanzhu_num = num
            }
        }
        var settings = ""
        if let name = nameTextF.text, name.count > 0 {
            settings = name
        }
        
        Task{
            ToastUtil.show()
            let models = await network.requestSpecial(.forumFollowSetting(gid: communityId, system_type: system_type, guanzhu_num: guanzhu_num, settings: settings))
            if models.isSuccess {
                "修改成功~".toast_success
                if settings.count == 0 {
                    settings = "未设置"
                }
                let model = ClubSquareSettingModel(title: "关注设置", content: settings, logo: guanzhu_num, bgImg: system_type)
                self.updateSquareSetting?(model)
                self.navigationController?.popViewController(animated: true)
            }else{
                models.errorMessage?.toast_error
            }
        }
    }
    
    @objc private func textFieldDidChange(_ textField: UITextField) {
        // 更新带有颜色的文本
        if let text = textField.text {
            textField.attributedText = createAttributedText(from: text)
        }
    }
    
    // 限制只能输入一个 #
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        // 判断是否已经包含 #，如果尝试输入第二个 #，阻止输入
        if string == "#" && (textField.text?.contains("#") ?? false) {
            return false
        }
        return true
    }
    
    private func createAttributedText(from text: String) -> NSAttributedString {
        let attributedString = NSMutableAttributedString(string: text)
        // 设置默认颜色
        attributedString.addAttribute(.foregroundColor, value: UIColor.black, range: NSRange(location: 0, length: attributedString.length))
        // 正则匹配所有 #
        let regex = try! NSRegularExpression(pattern: "#", options: [])
        let matches = regex.matches(in: text, options: [], range: NSRange(location: 0, length: (text as NSString).length))
            
        // 遍历匹配结果，设置颜色
        for (index, match) in matches.enumerated() {
            if index == 0 { // 只改变第一个 # 的颜色
                attributedString.addAttribute(.foregroundColor, value: "#FF7700".toColor, range: match.range)
            }
        }
        return attributedString
    }
}
